package async;

import jdk.internal.vm.Continuation;
import jdk.internal.vm.ContinuationScope;

// 1249 ms, r = 4995000000 java --add-opens java.base/jdk.internal.vm=ALL-UNNAMED -Xlog:gc=info,gc+heap=info:gc_loom.log:time async.Loom3Test
public class Loom3MultiTest {
	private static final int N1 = 10;
	private static final int N2 = 10;
	private static final int N3 = 1000000;
	private static final int N = N1 * N2 * N3;
	private static int s_i;
	private static final ContinuationScope cs = new ContinuationScope("VirtualThreads");

	private static void f3() {
		for (int i = 0; i < N3; i++) {
			s_i = i;
			Continuation.yield(cs);
		}
	}

	private static void f2() {
		for (int i = 0; i < N2; i++) {
//			f3();
			s_i = i;
			Continuation.yield(cs);
		}
	}

	private static void f1() {
		for (int i = 0; i < N1; i++)
			f2();
	}

	public static void main(String[] args) {
		long t = System.nanoTime();
		var ca = new Continuation[N3];
		for (int i = 0; i < N3; i++)
			ca[i] = new Continuation(cs, Loom3MultiTest::f1);
		long r = 0;
		for (int i = 0; i < N / N3; ++i) {
			for (int j = 0; j < N3; j++) {
				ca[j].run();
				r += s_i;
			}
		}
		System.out.println((System.nanoTime() - t) / 1_000_000 + " ms, r = " + r);
	}
}
